package com.hsj.common.system.controller;

import cn.hutool.crypto.SecureUtil;
import com.hsj.common.system.convert.SysUserConvert;
import com.hsj.common.system.entity.SysUserDo;
import com.hsj.common.system.service.ISysUserService;
import com.hsj.common.system.vo.request.ReqLoginVo;
import com.hsj.common.core.constants.ErrorCode;
import com.hsj.common.core.exception.BusinessException;
import com.hsj.common.security.ClientSecurityContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Api(tags = "系统接口")
@RestController
@RequestMapping("/system")
@Slf4j
public class SystemController {

    private final ISysUserService sysUserService;

    private final SysUserConvert sysUserConvert;

    private final ClientSecurityContext<SysUserDo> clientSecurityContext;


    public SystemController(ISysUserService sysUserService, SysUserConvert sysUserConvert, ClientSecurityContext<SysUserDo> clientSecurityContext) {
        this.sysUserService = sysUserService;
        this.sysUserConvert = sysUserConvert;
        this.clientSecurityContext = clientSecurityContext;
    }


    @PostMapping("login")
    @ApiOperation(value = "登录", notes = "管理员登录", httpMethod = "POST")
    public String login(@Valid @RequestBody ReqLoginVo vo){
        log.info("登录信息 userName={} pwd=******", vo.getUserName());
        String userName = vo.getUserName();
        String password = vo.getPassword();

        SysUserDo sysUserDo = sysUserService.loadByColumn(SysUserDo::getUserName, userName);
        if(sysUserDo == null){
            throw new BusinessException(ErrorCode.OAUTH2_INVALID_GRANT, "用户名密码错误");
        }
        String pwd = String.format("%s%s", password, sysUserDo.getSalt());
        pwd = SecureUtil.md5(pwd);
        if(!sysUserDo.getPassword().equals(pwd)){
            throw new BusinessException(ErrorCode.OAUTH2_INVALID_GRANT, "用户名密码错误");
        }
        return clientSecurityContext.login(sysUserDo);
    }


    @PostMapping("logout")
    @ApiOperation(value = "退出登录", notes = "管理员退出登录", httpMethod = "POST")
    public boolean logout(){
        return clientSecurityContext.logout();
    }


}
